package com.atguigu.demo.service;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;

public class AgeService {

    public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    private final String birthday;

    public AgeService(String birthday) {
        this.birthday = birthday;
    }

    public int computeAgeByBirthday() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);
        LocalDate birthDate = LocalDate.parse(birthday, formatter);
        LocalDate currentDate = LocalDate.now();

        // 检查生日是否在当前日期之后
        if (birthDate.isAfter(currentDate)) {
            return -1; // 无效的生日
        }

        // 计算年龄
        Period period = Period.between(birthDate, currentDate);
        return period.getYears();
    }
}
